﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenExpressApp.Types;
using OpenExpressApp.MetaModel;
using Itenso.Windows.Input;
using System.ComponentModel;

namespace OpenExpressApp.Module.WPF
{
    /// <summary>
    /// 查询面板
    /// </summary>
    public abstract class QueryObjectView : DetailObjectView
    {
        private ObjectView _resultView;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="boType">查询对象</param>
        /// <param name="resultView">查询后的结果使用的View</param>
        public QueryObjectView(Type boType, ObjectView resultView)
            : base(boType)
        {
            this._resultView = resultView;
            this.AttachNewQueryObject();
        }

        /// <summary>
        /// 查询后的结果使用的View
        /// </summary>
        public ObjectView ResultView
        {
            get
            {
                return this._resultView;
            }
        }

        public new IQueryObject CurrentObject
        {
            get
            {
                return base.CurrentObject as IQueryObject;
            }
            set
            {
                base.CurrentObject = value;
            }
        }

        protected override object CreateControl()
        {
            return AutoUI.UIFactory.CreateDetailView(this, 1);
        }

        /// <summary>
        /// 为这个查询面板构造并使用一个新的查询对象。
        /// </summary>
        /// <returns></returns>
        public object AttachNewQueryObject()
        {
            var data = Activator.CreateInstance(BOType);
            this.Data = data;
            return data;
        }

        /// <summary>
        /// 命令这个查询面板执行查询命令
        /// </summary>
        public void ExecuteQuery()
        {
            var queryObject = this.CurrentObject;
            queryObject.CheckRules();
            if (queryObject.BrokenRulesCollection.Count <= 0)
            {
                //查询出结果集是不是需要到服务器取数据。
                var resultBoInfo = ApplicationModel.GetBusinessObjectInfo(this._resultView.BOType);
                string commandName = resultBoInfo.NavigateQueryMode == NavigateQueryMode.Remote ? CommandNames.QueryObject : CommandNames.FilterObject;

                //执行命令
                var adapter = CommandRepository.NewCommand(commandName);
                var command = adapter.CoreCommand;
                if (command.CanExecute(this))
                {
                    command.Execute(this);
                }
            }
        }

        //protected override void OnCurrentObjectPropertyChanged(PropertyChangedEventArgs e)
        //{
        //    base.OnCurrentObjectPropertyChanged(e);
        //    //var currentObject = this.CurrentObject;
        //    //var type = currentObject.GetType();
        //    //var property = type.GetProperty(e.PropertyName);
        //}
    }
}